<template>
    <view class="homepage">
        <view class="search-group">
            <u-search placeholder="请输入服务单号" v-model="queryParams.serviceNo" clearabled @custom="handleSearchList"
                @clear="handleSearchList"></u-search>
            <text class="advanced-search-btn" @click="openPopup">高级</text>
        </view>
        <scroll-view scroll-y class="scroll-list-view" @scrolltolower="loadMore" lower-threshold="50">
            <view class="search-result" v-if="searchResult.length > 0">
                <view class="search-item" v-for="item in searchResult" :key="item.id">
                    <view style="display:flex;justify-content: space-between;align-items: center;margin-bottom:-10rpx">
                        <text @longpress="copyText(item.serviceNo)">{{ item.serviceNo }}</text>
                        <text style="color:#409eff;font-size:14px;font-weight:bold;padding:10px" @click="
                        goPageByPath('/pages/index/child',{serviceNo: item.serviceNo})">明细</text>
                    </view>
                    <view class="search-item-info">
                        <view>
                            <text class="search-item-info-title">客户名称:</text>
                            <text class="ml-10">{{ item.customerName }}</text>
                        </view>
                    </view>
                    <view class="search-item-info">
                        <view>
                            <text class="search-item-info-title">经销商:</text>
                            <text class="ml-10" @longpress="copyText(item.dealerName)"> {{ item.dealerName }}</text>
                        </view>
                    </view>
                    <view class="search-item-info ">
                        <view>
                            <text class="search-item-info-title">价格:</text>
                            <text class="ml-10">{{ item.serviceMoney }}</text>
                        </view>
                    </view>
                    <view class="search-item-info ">
                        <view>
                            <text class="search-item-info-title">车架号:</text>
                            <text class="ml-10" @longpress="copyText(item.frameNumber)">{{ item.frameNumber }}</text>
                        </view>
                    </view>
                    <view class="search-item-info">
                        <view>
                            <text class="search-item-info-title">证件号码:</text>
                            <text class="ml-10" @longpress="copyText(item.certificateNumber)">{{ item.certificateType }}-{{
                            item.certificateNumber }}</text>
                        </view>
                    </view>
                    <view class="search-item-info">
                        <view>
                            <text class="search-item-info-title">销售日期:</text>
                            <text class="ml-10">{{ item.saleDate }}</text>
                        </view>
                    </view>

                    <view class="search-item-btns">
                        <u-button type="primary" text="编辑" size="mini"
                            @click="goPageByPath('/pages/index/service?id=' + item.id)"></u-button>
                        <!-- <u-button type="error" text="删除" size="mini"></u-button> -->
                        <u-button type="warning" text="预览" size="mini"
                            @click="goPageByPath('/pages/index/previewPdf',{id: item.id})"> </u-button>
                        <u-button type="success" text="下载" size="mini" @click="downloadPdf(item)"></u-button>
                    </view>
                </view>
            </view>
            <view class="no-search" v-else>
                <u-empty mode="list" marginTop="120" text="暂无数据" />
            </view>
        </scroll-view>

        <!-- 添加按钮 -->
        <view class="add_btn" @click="goPageByPath('/pages/index/service')">
            <u-icon name="plus" color="#fff" size="38"></u-icon>
        </view>

        <!-- 高级搜索 -->
        <uni-popup v-if="isLoaded" class="index-uni-popup" ref="advanceSearchPopup" background-color="#fff"
            borderRadius="6px">
            <view class="advanced-search">
                <u--form labelWidth="auto" labelPosition="top" :model="queryParams" ref="queryParams">
                    <u-form-item label="销售日期" prop="beginTime">
                        <uni-datetime-picker type="date" :clear-icon="true" v-model="queryParams.beginTime"
                            :end="queryParams.endTime"
                            @change="e => timeChange({ val: e, formKey: 'queryParams', key: 'beginTime' })"
                            placeholder="开始日期" />
                        <text class="separator">
                            -
                        </text>
                        <uni-datetime-picker type="date" :clear-icon="true" v-model="queryParams.endTime"
                            :start="queryParams.beginTime"
                            @change="e => timeChange({ val: e, formKey: 'queryParams', key: 'endTime' })"
                            placeholder="结束日期" />
                    </u-form-item>
                    <u-form-item label="经销商" prop="dealerId">
                        <uni-combox style="width:100%;margin-top:1px" labelKey="dealerName" valueKey="id"
                            :candidates="dealerSelectList" :remoteFn="dealerInput" placeholder="请选择经销商"
                            v-model="queryParams.dealerId"></uni-combox>
                    </u-form-item>
                    <u-form-item label="GPS序列号" prop="gps">
                        <u--input placeholder="请输入GPS序列号" border="surround" v-model="queryParams.gps"></u--input>
                    </u-form-item>
                    <u-form-item label="客户姓名" prop="customerName">
                        <u--input placeholder="请输入客户姓名" border="surround" v-model="queryParams.customerName"></u--input>
                    </u-form-item>
                    <u-form-item label="车架号" prop="frameNumber">
                        <u--input placeholder="请输入车架号" border="surround" v-model="queryParams.frameNumber"></u--input>
                    </u-form-item>
                    <u-form-item label="业务类型" prop="businessId">
                        <uni-combox style="width:100%" labelKey="businessName" valueKey="id"
                            :candidates="businessSelectList" placeholder="请选择业务类型"
                            v-model="queryParams.businessId"></uni-combox>
                    </u-form-item>
                    <u-form-item label="客户证件" prop="certificateNumber">
                        <u--input placeholder="请输入车架号" border="surround"
                            v-model="queryParams.certificateNumber"></u--input>
                    </u-form-item>
                    <u-form-item label="用户名" prop="createBy">
                        <u--input placeholder="请输入用户名" border="surround" v-model="queryParams.createBy"></u--input>
                    </u-form-item>
                    <u-form-item>
                        <u-button style="width:45%" type="success" text="重置" @click="resetForm"></u-button>
                        <u-button style="width:45%" type="primary" text="确定" @click="submitForm"></u-button>
                    </u-form-item>
                </u--form>
            </view>
        </uni-popup>
    </view>
</template>

<script>
import { listService, orderPdfDownload } from "@/utils/api";
import commonMixin from "@/mixins/common";
import { base64Encode } from "@/utils";
import EventBus from "@/utils/eventBus";

export default {
    mixins: [commonMixin],
    data() {
        return {
            queryParams: {
                pageSize: 20,
                pageNum: 1,
                beginTime: null,
                endTime: null,
                serviceNo: null,
                dealerId: null,
                gps: null,
                customerName: null,
                frameNumber: null,
                businessId: null,
                certificateNumber: null,
                createBy: null,
            },
            copyQueryParams: {},
            dealerSelectList: [], // 经销商下拉
            businessSelectList: [], // 业务类型下拉

            searchResult: [], //列表
            hasMore: true, //是否有更多数据
            isLoaded: false,
        };
    },
    onShow() {},
    onLoad() {
        this.getList();
    },
    mounted() {
        this.isLoaded = true;
    },
    created() {
        EventBus.$on("refreshServiceList", this.initLoadData);
    },
    beforeDestroy() {
        EventBus.$off("refreshServiceList", this.initLoadData);
    },

    methods: {
        loadMore() {
            if (this.hasMore) {
                this.queryParams.pageNum++;
                this.getList();
            } else {
                // this.$u.toast("没有更多数据了");
            }
        },
        initLoadData() {
            this.resetQueryParams();
            this.searchResult = [];
            this.hasMore = true;
            this.getList();
        },

        resetQueryParams() {
            this.queryParams = {
                pageSize: 20,
                pageNum: 1,
                beginTime: null,
                endTime: null,
                serviceNo: null,
                dealerId: null,
                gps: null,
                customerName: null,
                frameNumber: null,
                businessId: null,
                certificateNumber: null,
                createBy: null,
            };
        },

        async getList() {
            try {
                uni.showLoading({ title: "加载", mask: true });
                let res = await listService({
                    params: this.queryParams,
                    custom: { catch: true },
                });
                this.searchResult = [...this.searchResult, ...res.rows];
                if (this.searchResult.length >= res.total) {
                    this.hasMore = false;
                }
                uni.hideLoading({});
            } catch (error) {
                uni.hideLoading({});
            }
        },

        // 打开高级搜索
        async openPopup() {
            this.$refs.advanceSearchPopup.open("center");
            // 获取业务类型下拉
            await this.getCommonSelectList({
                listKey: "businessSelectList",
                api: this.apis.listBusiness2,
            });
        },

        // 经销商输入变化事件
        dealerInput(val) {
            if (!val) {
                this.dealerSelectList = [];
                this.queryParams.dealerId = null;
                return;
            }
            this.$u.debounce(async () => {
                await this.getCommonSelectList({
                    listKey: "dealerSelectList",
                    api: this.apis.listDealer2,
                    extra: { dealerName: val },
                });
            }, 400);
        },

        // 长摁复制
        async copyText(text) {
            uni.setClipboardData({
                data: text,
                success: () => {
                    this.$u.toast(`已复制到粘贴板`);
                },
            });
        },

        handleSearchList() {
            this.queryParams.pageNum = 1;
            this.searchResult = [];
            this.hasMore = true;
            this.getList();
        },

        resetForm() {
            let excludeKeys = ["pageNum", "pageSize"];
            Object.keys(this.queryParams).forEach((key) => {
                if (!excludeKeys.includes(key)) {
                    this.queryParams[key] = null;
                }
            });
            this.$u.toast("已重置");
        },

        submitForm() {
            this.handleSearchList();
            this.$refs.advanceSearchPopup.close();
        },

        async downloadPdf(record) {
            try {
                this.$u.toast("下载中,请等待");
                let res = await orderPdfDownload({
                    params: { id: record.id },
                    responseType: "arraybuffer",
                    custom: { catch: true },
                });
                let blob = new Blob([res], {
                    type: "application/pdf;charset=UTF-8",
                });
                let aLink = document.createElement("a");
                let aLinkHref = window.URL.createObjectURL(blob);
                aLink.href = aLinkHref;
                aLink.download = `${record.customerName}_${record.serviceNo}.pdf`;
                aLink.click();
                aLink.remove();
                window.URL.revokeObjectURL(aLinkHref);
            } catch (error) {
                this.$u.toast("下载失败");
            }
        },
    },
};
</script>

<style lang='scss' scoped>
uni-page-body {
    width: 100%;
    height: 100%;
    background: #f4f4f4;
}

.homepage {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
}
::v-deep .scroll-list-view {
    flex: 1;
    overflow: auto;
    background: #f4f4f4;
    .uni-scroll-view-content {
        height: auto;
    }
}

.search-group {
    background: #fff;
    padding: 10px;
    display: flex;
    align-items: center;

    .advanced-search-btn {
        font-size: 14px;
        color: #303133;
        padding: 0 10rpx;
    }
}

::v-deep .advanced-search {
    padding: 20px;
    .uni-combox {
        border: 1px solid #dadbde !important;
        padding: 7px 10px;
    }
    .u-input {
        border: 1px solid #dadbde !important;
    }
}

::v-deep .advanced-search-popup {
    .u-popup__content {
        width: 85%;
        height: 1200rpx;
        overflow: auto;
    }
}

::v-deep .search-item-popup {
    .u-popup__content {
        width: 85%;
        height: 1200rpx;
        overflow: auto;
        background: #f4f4f4;
    }
}

.separator {
    padding: 0 20rpx;
}

.no-search {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.search-result {
    background: #f4f4f4;
}

.search-item {
    background: #fff;
    margin-bottom: 20rpx;
    padding: 8rpx 20rpx 28rpx;
    &:first-of-type {
        margin-top: 20rpx;
    }

    &-info {
        color: #666;
        font-size: 14px;
        display: flex;
        justify-content: space-between;
        margin-top: 12rpx;

        &:nth-of-type(1) {
            margin-top: 0;
        }

        &.info-s {
            > view {
                width: 50%;
            }
        }

        .ml-10 {
            margin-left: 10px;
        }

        &-title {
            display: inline-block;
        }
    }
}

.search-item-btns {
    display: flex;
    justify-content: flex-end;
    padding-top: 14px;
    margin-top: 10px;
    border-top: 1px solid #f4f4f4;

    .u-button {
        margin: 0;
        width: 20px;

        & ~ .u-button {
            margin-left: 12px;
        }
    }
}

.add_btn {
    position: fixed;
    right: 50rpx;
    bottom: 240rpx;
    width: 100rpx;
    height: 100rpx;
    border-radius: 100rpx;
    box-shadow: 0 0 12rpx #a0a0a0;
    background: #007aff;
    display: flex;
    align-items: center;
    justify-content: center;
}

::v-deep .index-uni-popup {
    z-index: 1000;
    .uni-popup__wrapper {
        width: 85%;
        height: 1200rpx;
        overflow: auto;
    }
}
</style>
